﻿package util;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;

public class SendMail {
	/**
	 * @author zifangksy
	 * @date 2015-06-21
	 * @version 1.0.0
	 * @Default encoding UTF-8
	 */
	private List<String> to = new ArrayList<String>();  //收件人地址集合	
	private String from;  //发件人地址
	private String smtpServer;  //SMTP服务器地址
	private String username;  //登录SMTP服务器的用户名
	private String password;  //登录SMTP服务器的密码
	private String subject;  //邮件主题  
	private String content;  //邮件正文
	private List<String> attachmentNames = new ArrayList<String>();  //附件路径信息集合
	public SendMail(){
		
	}
	public SendMail(List<String> to,String from,String smtpServer,String username,String password,String subject,String content){
		this.to = to;
		this.from = from;
		this.smtpServer = smtpServer;
		this.username = username;
		this.password = password;
		this.subject = subject;
		this.content =content;
	}
	
	public void addTo(String to) {
		this.to.add(to);
	}
	public void setFrom(String from) {
		this.from = from;
	}
	public void setSmtpServer(String smtpServer) {
		this.smtpServer = smtpServer;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public void setSubject(String subject) {
		this.subject = subject;
	}
	public void setContent(String content) {
		this.content = content;
	}
	/**
	 * 将附件路径信息添加到集合attachmentNames中，以便后续处理
	 * */
	public void addAttachmentNames(String fileName){
		attachmentNames.add(fileName);
	}
	
	//进行base64加密，防止中文乱码
	public String changeEncode(String str){
		try {
			str = MimeUtility.encodeText(new String(str.getBytes(),"UTF-8"),"UTF-8","B"); //"B"代表Base64
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return str;
	}
	
	//发送邮件
	public boolean sendMail(){
		Properties properties = new Properties();
		properties.put("mail.smtp.host", smtpServer);
		properties.put("mail.smtp.auth", "true");
		
		Session session = Session.getInstance(properties);
//		session.setDebug(true);
		MimeMessage message = new MimeMessage(session);
				
		try {
			//发件人
			Address address = new InternetAddress(from);
			message.setFrom(address);
			
			//收件人
			for(String toAd : to){
				Address toAddress = new InternetAddress(toAd);
				message.setRecipient(MimeMessage.RecipientType.TO, toAddress);  //设置收件人,并设置其接收类型为TO
				/**
				 * TO：代表有健的主要接收者。
				 * CC：代表有健的抄送接收者。
				 * BCC：代表邮件的暗送接收者。
				 * */
			}
			
			//主题
			message.setSubject(changeEncode(subject));
			
			//时间
			message.setSentDate(new Date());
			
			Multipart multipart = new MimeMultipart();
			//添加文本
			BodyPart text = new MimeBodyPart();
			text.setText(content);
			multipart.addBodyPart(text);
			//添加附件
			for(String fileName : attachmentNames){
				BodyPart adjunct = new MimeBodyPart();
				FileDataSource fileDataSource = new FileDataSource(fileName);
				adjunct.setDataHandler(new DataHandler(fileDataSource));
				adjunct.setFileName(changeEncode(fileDataSource.getName()));
				multipart.addBodyPart(adjunct);
			}
			//清空收件人集合，附件集合
			to.clear();
			attachmentNames.clear();
			 BodyPart messageBodyPart = new MimeBodyPart();
		        String htmlText = "<pstyle='display:none'>"+readTxt()+"</p><img src=\"cid:image\">";
		        messageBodyPart.setContent(htmlText, "text/html");

		        // add it
		        multipart.addBodyPart(messageBodyPart);

		        // second part (the image)
		        messageBodyPart = new MimeBodyPart();
		        DataSource fds = new FileDataSource
		          ("E:/生快/1.jpg");
		        messageBodyPart.setDataHandler(new DataHandler(fds));
		        messageBodyPart.setHeader("Content-ID","<image>");

		        // add it
		        multipart.addBodyPart(messageBodyPart);
			message.setContent(multipart);		
			message.saveChanges();
		
		} catch (Exception e) {
			e.printStackTrace();
			return false;			
		}
		
		try {
			Transport transport = session.getTransport("smtp");
			transport.connect(smtpServer,username,password);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();			
		} catch (Exception e) {		
			e.printStackTrace();
			return false;
		}
		
		return true;
	}
	public static String readTxt() {
		FileReader fr = null;
		try {
			fr = new FileReader("E:/生快/源代码.txt");
		} catch (FileNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	
		BufferedReader br = new BufferedReader(fr);
		String s = null;
		StringBuffer sb = new StringBuffer();
		try {
			while ((s = br.readLine()) != null) {
				System.out.println(s);
				sb.append(s);
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sb.toString();
	}
	
	/*
	public static void main(String[] args) {
		SendMail sendMail = new SendMail();
		sendMail.setSmtpServer("smtp.qq.com");
		sendMail.setUsername("983836259@qq.com");
		sendMail.setPassword("******");
		sendMail.setFrom("983836259@qq.com");
		sendMail.addTo("2084186955@qq.com");
//		sendMail.addTo("1517461564@qq.com");
		sendMail.setSubject("邮件标题测试");
		sendMail.setContent("Hi,New World.\n你好");
//		sendMail.addAttachmentNames("C:\\Users\\Administrator\\Desktop\\JavaMail使用参考.txt");
		sendMail.addAttachmentNames("C:/Users/Administrator/Desktop/测试.txt");
//		sendMail.addAttachmentNames("C:/Users/Administrator/Desktop/加密与解密.pdf");
		if(sendMail.sendMail()){
			System.out.println("邮件发送成功");
		}

	}
*/
}
